/*
 * @Author: ZhanXie
 * @Date: 2019-11-25 18:36:53
 * @LastEditors: ZhanXie
 * @LastEditTime: 2019-12-02 15:31:51
 * @Description: 用户 路由
 * @FilePath: /node-demo/blog-origin/src/router/user.js
 */
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { login } = require('../controller/user')
const { get, set } = require('../db/redis')

const handleUserRouter = (req, res) => {
  const method = req.method // GET POST

  // 登录
  if (method === 'POST' && req.path === '/api/user/login') {
    const { username, password } = req.body
    // const { username, password } = req.query
    const result = login(username, password)
    return result.then(data => {
      if (data.username) {
        // 设置 session
        req.session.username = data.username
        req.session.realname = data.realname

        // 同步到redis
        set(req.sessionId, req.session)
        return new SuccessModel(data)
      }
      return new ErrorModel('登录失败')
    })
  }

  // 登录验证的测试
  if (method === 'GET' && req.path === '/api/user/login-test') {
    if (req.session.username) {
      return Promise.resolve(new SuccessModel({
        username: req.session.username
      }))
    }
    return Promise.resolve(new ErrorModel('尚未登录'))
  }
}

module.exports = handleUserRouter